package com.css.zfzx.fxpg.modules.percent.economicloss.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.org.division.repository.entity.DivisionEntity;
import com.css.zfzx.fxpg.common.utils.BeanUtil;
import com.css.zfzx.fxpg.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.fxpg.modules.casulaty.probability.repository.entity.FxCasulatyProbabilityEntity;
import com.css.zfzx.fxpg.modules.percent.casualty.repository.entity.FxCasualtyPercentEntity;
import com.css.zfzx.fxpg.modules.percent.casualty.viewobjects.FxCasualtyPercentQueryParams;
import com.css.zfzx.fxpg.modules.percent.casualty.viewobjects.FxCasualtyPercentVO;
import com.css.zfzx.fxpg.modules.percent.daynight.repository.entity.FxDayNightPercentEntity;
import com.css.zfzx.fxpg.modules.percent.daynight.viewobjects.FxDayNightPercentVO;
import com.css.zfzx.fxpg.modules.percent.economicloss.repository.FxEconomicLossNativeRepository;
import com.css.zfzx.fxpg.modules.percent.economicloss.repository.FxEconomicLossRepository;
import com.css.zfzx.fxpg.modules.percent.economicloss.repository.entity.FxEconomicLossEntity;
import com.css.zfzx.fxpg.modules.percent.economicloss.service.FxEconomicLossService;
import com.css.zfzx.fxpg.modules.percent.economicloss.viewobjects.FxEconomicLossQueryParams;
import com.css.zfzx.fxpg.modules.percent.economicloss.viewobjects.FxEconomicLossVO;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author leon
 * @date 2020-11-17
 */
@Service
@Slf4j
public class FxEconomicLossServiceImpl implements FxEconomicLossService {

    @Autowired
    private FxEconomicLossRepository fxEconomicLossRepository;
    @Autowired
    private FxEconomicLossNativeRepository fxEconomicLossNativeRepository;

    @Override
    public JSONObject queryFxEconomicLosss(FxEconomicLossQueryParams queryParams, int curPage, int pageSize) {
        Page<FxEconomicLossEntity> fxEconomicLossPage = this.fxEconomicLossNativeRepository.queryFxEconomicLosss(queryParams, curPage, pageSize);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(fxEconomicLossPage);
        return jsonObject;
    }


    @Override
    public FxEconomicLossEntity getFxEconomicLoss(String id) {
        FxEconomicLossEntity fxEconomicLoss = this.fxEconomicLossRepository.findById(id).orElse(null);
        return fxEconomicLoss;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FxEconomicLossEntity saveFxEconomicLoss(FxEconomicLossEntity fxEconomicLoss) {
        String uuid = UUIDGenerator.getUUID();
        fxEconomicLoss.setId(uuid);
        fxEconomicLoss.setCreateUser(PlatformSessionUtils.getUserId());
        fxEconomicLoss.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        this.fxEconomicLossRepository.save(fxEconomicLoss);
        return fxEconomicLoss;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FxEconomicLossEntity updateFxEconomicLoss(FxEconomicLossEntity fxEconomicLoss) {
        fxEconomicLoss.setUpdateUser(PlatformSessionUtils.getUserId());
        fxEconomicLoss.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        String id = fxEconomicLoss.getId();
        FxEconomicLossEntity one = fxEconomicLossRepository.findById(id).get();
        BeanUtil.copyPropertiesIgnoreNull(fxEconomicLoss, one);
        this.fxEconomicLossRepository.save(one);
        return fxEconomicLoss;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteFxEconomicLosss(List<String> ids) {
        List<FxEconomicLossEntity> fxEconomicLossList = this.fxEconomicLossRepository.findAllById(ids);
        if (!PlatformObjectUtils.isEmpty(fxEconomicLossList) && fxEconomicLossList.size() > 0) {
            for (FxEconomicLossEntity fxEconomicLoss : fxEconomicLossList) {
                this.fxEconomicLossRepository.delete(fxEconomicLoss);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public List<FxEconomicLossEntity> listFxEconomicLosss(FxEconomicLossQueryParams queryParams) {
        return fxEconomicLossNativeRepository.listFxEconomicLosss(queryParams);
    }

    @Override
    public void initialize() {
        List<FxEconomicLossEntity> all = fxEconomicLossRepository.findAll();
        if (all != null && all.size() > 0) {
            throw new RuntimeException("请删除所有数据后进行初始化！");
        } else {
            List<DivisionEntity> provinceDivisions = PlatformAPI.getDivisionAPI().getSubDivisions("root");
            for (DivisionEntity provinceDivision : provinceDivisions) {
                // 省
                String province = provinceDivision.getDivisionName();
                // 直辖市
                if ("北京市".equals(province) || "天津市".equals(province) || "上海市".equals(province) || "重庆市".equals(province)) {
                    // 市
                    String city = province;
                    List<DivisionEntity> areaDivisions = PlatformAPI.getDivisionAPI().getSubDivisions(provinceDivision.getDivisionId());
                    for (DivisionEntity areaDivision : areaDivisions) {
                        FxEconomicLossEntity entity = new FxEconomicLossEntity();
                        // 区
                        String area = areaDivision.getDivisionName();
                        entity.setProvince(province);
                        entity.setCity(city);
                        entity.setArea(area);
                        // 类型字典值并且保存
                        saveInitialize(entity);
                    }
                    // 临时只添加一个直辖市
                    break;
                }
                // 省下面的正常市
                else {
                    List<DivisionEntity> cityDivisions = PlatformAPI.getDivisionAPI().getSubDivisions(provinceDivision.getDivisionId());
                    for (DivisionEntity cityDivision : cityDivisions) {
                        // 市
                        String city = cityDivision.getDivisionName();
                        List<DivisionEntity> areaDivisions = PlatformAPI.getDivisionAPI().getSubDivisions(cityDivision.getDivisionId());
                        for (DivisionEntity areaDivision : areaDivisions) {
                            // 区
                            String area = areaDivision.getDivisionName();
                            FxEconomicLossEntity entity = new FxEconomicLossEntity();
                            entity.setProvince(province);
                            entity.setCity(city);
                            entity.setArea(area);
                            // 类型字典值并且保存
                            saveInitialize(entity);
                        }
                    }
                }
                // 临时添加数据，只添加北京的；正式时候去掉break
                break;
            }
        }
    }

    @Override
    public String exportExcel(FxEconomicLossQueryParams queryParams, HttpServletResponse response) {
        try {
            List<FxEconomicLossEntity> entities = fxEconomicLossNativeRepository.listFxEconomicLosss(queryParams);
            // 深拷贝
            ArrayList<FxEconomicLossVO> vos = new ArrayList<>();
            for (FxEconomicLossEntity entity : entities) {
                FxEconomicLossVO vo = new FxEconomicLossVO();
                BeanUtils.copyProperties(entity, vo);
                vos.add(vo);
            }
            // 导出
            EasyPoiExcelUtil.exportExcel(vos, "重置单价", "重置单价", FxEconomicLossVO.class, "重置单价.xlsx", response);
            return "导出成功";
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

    @Override
    public String importExcel(MultipartFile file) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            params.setTitleRows(1);
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<FxEconomicLossVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), FxEconomicLossVO.class, params);
            List<FxEconomicLossVO> list = result.getList();
            // 批量新增
            this.saveExcel(list);
            returnMsg.append("成功导入" + result.getList().size() + "条，失败" + result.getFailList().size() + "条<br/>");
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<FxEconomicLossVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    FxEconomicLossVO vo = iterator.next();
                    String error = "";
                    returnMsg.append("第" + vo.getRowNum() + "行" + vo.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            if ("库中该数据最多一条，请管理员清理数据库冗余数据！".equals(e.getMessage())) {
                return e.getMessage();
            } else {
                return "导入失败，请检查数据正确性";
            }
        }
    }

    private void saveExcel(List<FxEconomicLossVO> list) {
        for (int i = 0; i < list.size(); i++) {
            FxEconomicLossEntity entity = new FxEconomicLossEntity();
            FxEconomicLossVO vo = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(vo, entity);
            saveOrUpdate(entity);
        }
    }

    private void saveOrUpdate(FxEconomicLossEntity entity) {
        FxEconomicLossQueryParams queryParams = new FxEconomicLossQueryParams();
        queryParams.setProvince(entity.getProvince());
        queryParams.setCity(entity.getCity());
        queryParams.setArea(entity.getArea());
        queryParams.setStructureType(entity.getStructureType());

        List<FxEconomicLossEntity> entityList = fxEconomicLossNativeRepository.listFxEconomicLosss(queryParams);
        // 若查到数据为空，则新增
        if (CollectionUtils.isEmpty(entityList)) {
            this.saveFxEconomicLoss(entity);
        } else {
            if (entityList.size() == 1) {
                // 修改
                FxEconomicLossEntity sourceEntity = entityList.get(0);
                BeanUtil.copyPropertiesIgnoreNull(entity, sourceEntity);
                this.updateFxEconomicLoss(sourceEntity);
            } else {
                throw new RuntimeException("库中该数据最多一条，请管理员清理数据库冗余数据！");
            }
        }
    }

    private void saveInitialize(FxEconomicLossEntity entity) {
        // 破坏程度
        List<DictItemEntity> structureTypes = PlatformAPI.getDictAPI().getValidDictItemsByDictCode("structureType");
        for (int i = 0; i < structureTypes.size(); i++) {
            String structureType = structureTypes.get(i).getDictItemCode();
            entity.setStructureType(structureType);
            this.saveFxEconomicLoss(entity);
        }
    }

}
